package com.example.exam.conf.security;

import com.example.exam.entity.User;
import com.example.exam.utils.Md5Utils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhang
 */
@Service
@Log4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        List<User> user = userRepository.findByAccount(account);
        List<GrantedAuthority> list = new ArrayList<>();
        if (user.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在");
        }
        log.info(user);
        user.get(0).setPassword(user.get(0).getPassword() + user.get(0).getSalt());
        list.add(new SimpleGrantedAuthority(user.get(0).getRole_id().toString()));
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.get(0).getId() + user.get(0).getPassword())
                .password(user.get(0).getPassword())
                .authorities(list)
                .build();
        return userDetails;
    }
}
